package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.view.View;

import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.sgb.capital.R;
import com.sgb.capital.api.CapitalManager;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.OnZTabSelectedListener;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.FinanceflowActivityBinding;
import com.sgb.capital.model.BaseEntity;
import com.sgb.capital.model.InvoiceStatisticInfo;
import com.sgb.capital.utils.DialogHelper;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.adapter.ViewPagerAdapter;
import com.sgb.capital.view.ui.fragment.CostQueryFragment;
import com.sgb.capital.view.ui.fragment.FinanceFlowFragment;
import com.sgb.capital.view.widget.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者:张磊
 * 日期:2021/4/7 0007
 * 说明:财务流水和费用查询
 */
public class FinanceFlowAndCostQueryActivity extends BaseActivity {

    private FinanceflowActivityBinding mBinding;
    public boolean mUser;
    private int mIndex;
    private ViewPagerAdapter viewPagerAdapter;

    public static void start(Context context, boolean isUser,int index) {
        Intent intent = new Intent(context, FinanceFlowAndCostQueryActivity.class);
        intent.putExtra("user", isUser);
        intent.putExtra("index", index);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mUser = getIntent().getBooleanExtra("user", false);
        mIndex = getIntent().getIntExtra("index", 0);
        Utils.setStatusBarLightMode(this, true);
        mBinding = DataBindingUtil.setContentView(this, R.layout.financeflow_activity);
        mBinding.tvTitle.setText(mIndex==0? "账务流水":"费用查询");
        mBinding.tvGetInvoice.setVisibility(mIndex == 0 ? View.GONE : View.VISIBLE);
    }

    @Override
    public void initData() {
        initTab(new String[]{"全部流水", "费用查询"});
    }

    private void initTab(String[] titls) {
        List<Pair<String, Fragment>> mList = new ArrayList<>();
        for (String s : titls) {
            mList.add(new Pair<>(s, s.contains("全部流水") ? new FinanceFlowFragment() : new CostQueryFragment()));
        }
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mList);
        mBinding.vpNeed.setAdapter(viewPagerAdapter);
        mBinding.vpNeed.setOffscreenPageLimit(titls.length);
        mBinding.tab.setupWithViewPager(mBinding.vpNeed);
        mBinding.vpNeed.setCurrentItem(mIndex);
        mBinding.tab.getTabAt(mIndex).select();
    }


    @Override
    public void initListener() {
        super.initListener();
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.tab.addOnTabSelectedListener(new OnZTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                mBinding.tvTitle.setText(tab.getPosition()==0? "账务流水":"费用查询");
                mBinding.tvGetInvoice.setVisibility(tab.getPosition()==0 ? View.GONE : View.VISIBLE);
                if (tab==null|| tab.getText()==null){
                    return;
                }
                String trim = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(trim);
                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                spannableString.setSpan(styleSpan,0,trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spannableString);


            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab==null|| tab.getText()==null){
                    return;
                }
                String trim = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(trim);
                StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);
                spannableString.setSpan(styleSpan,0,trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spannableString);
            }
        });
        mBinding.tvGetInvoice.setOnClickListener(v -> {
            getInvoiceStatisticInfo();
        });
    }

    /** 统计可开具流水数量和金额 */
    private void getInvoiceStatisticInfo() {
        DialogHelper.showProgressDialog(FinanceFlowAndCostQueryActivity.this, "数据加载中").setCanceledOnTouchOutside(false);
        CapitalManager.getInstance().getCapitalAPI().getInvoiceStatisticInfo(new InvoiceStatisticInfo()).enqueue(new Callback<BaseEntity<InvoiceStatisticInfo>>() {

            @Override
            public void onResponse(Call<BaseEntity<InvoiceStatisticInfo>> call, Response<BaseEntity<InvoiceStatisticInfo>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(CapitalManager.RESPONSE_OK)) {
                    checkHasCostListCount(response.body().getData().number);
                } else {
                    MToast.showToast(getApplication(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<InvoiceStatisticInfo>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }

    /** 索取发票入口跳转 (点击索取发票判断当前账户有无可开票费用；若有则跳转至选择流水页面；若无，则弹出弹窗提示) */
    private void checkHasCostListCount(long count) {
        if(count <= 0) {
            new TipPop(FinanceFlowAndCostQueryActivity.this,
                    "温馨提示",
                    "无可开票费用",
                    null,
                    "知道了").show();
        } else {
            InvoiceFlowActivity.start(FinanceFlowAndCostQueryActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        Utils.sendMsg(Constants.EVENT_REFRESH, null);
        super.onDestroy();
    }

    @Subscribe
    public void confirmInvoiceJumpAsiaRecord(ZMessageEvent event) {
        if(Constants.EVENT_CONFIRM_INVOICE_JUMP_ASIA_RECORD == event.code) {
            AsiaRecordActivity.start(FinanceFlowAndCostQueryActivity.this);
            finish();
        }
    }
}